package me.shurufa.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import me.shurufa.MainApplication;
import me.shurufa.R;
import me.shurufa.activities.BaseActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.activities.ShareActivity;
import me.shurufa.db.PersistenceUtils;

/**
 * 通用工具类
 *
 * @FileName: me.shurufa.utils.Utils.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-14 12:28
 */
public class Utils {

    /**
     * 首先默认个文件保存路径
     */
    private static final String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)
            ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard"; //保存到SD卡
    private static final String SAVE_REAL_PATH = SAVE_PIC_PATH + "/shurufa/excerptImages";        //保存的确切位置

    public static final int ONE_MINUTE = 60 * 1000;
    public static final int ONE_HOUR = 60 * 60 * 1000;
    public static final Charset CHARSET = Charset.forName("UTF-8");
    public static final int BUFFER_SIZE = 4096;

    private static long lastOneClickTime = 0;// click事件的基准时间

    public static boolean isFastClick(int timeMillis) {
        long time = System.currentTimeMillis();
        long timeD = time - lastOneClickTime;
        lastOneClickTime = time;
        if (timeD > timeMillis) {
            return false;
        }
        return true;
    }

//long型时间工具类，如果是今天显示准确时间 如果不是今天显示日期

    public static String getDatetimeStr(long time) {
        Date date = new Date(time);
        if (isToday(date)) {
            return todayFormat.get().format(date);
        } else {
            return dateFormat.get().format(date);
        }
    }

    public static boolean isToday(Date date) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date);
        return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2
                .get(Calendar.MONTH) && c1.get(Calendar.DAY_OF_MONTH) == c2
                .get(Calendar.DAY_OF_MONTH);
    }

    private static final ThreadLocal<DateFormat> todayFormat = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    };

    private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }
    };

    /**
     * 获取手机Imei码
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        try {
            return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getDeviceId();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 读取文件流
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String readStream(BufferedInputStream inputStream) throws IOException {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[BUFFER_SIZE];
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            return new String(byteArrayOutputStream.toByteArray(), CHARSET.name());
        } catch (Exception e) {
            return "";
        } catch (Error e) {
            return "";
        } finally {
            inputStream.close();
        }
    }

    /**
     * 关闭文件流
     *
     * @param closeable
     */
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception ignored) {

        }
    }

    public static void showToast(int resId) {
        // Toast.makeText(MainApplication.getInstance(), resId, Toast.LENGTH_SHORT).show();
        String text = MainApplication.getInstance().getString(resId);
        showToast_inner(MainApplication.getInstance(), text).show();
    }

    public static void showToast(String msg) {
        // Toast.makeText(MainApplication.getInstance(), msg, Toast.LENGTH_SHORT).show();
        showToast_inner(MainApplication.getInstance(), msg).show();
    }

    private static Toast t;

    private static Toast showToast_inner(Context context, String text) {
        TextView tv;
        if (t != null) {
            //t.cancel();
            tv = (TextView) t.getView();
        } else {
            tv = new TextView(context);
            tv.setBackgroundResource(R.drawable.shape_toast);
            tv.setTextSize(14.0f);
            tv.setTextColor(Color.WHITE);
        }
        tv.setText(text);
        if (t != null) {
            t.setView(tv);
            t.show();
        } else {
            t = new Toast(context);
            t.setView(tv);
            t.setDuration(Toast.LENGTH_SHORT);
            t.show();
        }
        return t;
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) ((dpValue * scale) + 0.5f);
    }

    public static Bitmap compressImageFromFile(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = 480f;//
        float ww = 320f;//
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置采样率

        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
        //其实是无效的,大家尽管尝试
        return bitmap;
    }

    /**
     * yyyy-MM-dd HH:mm:ss转yyyy-MM-dd
     *
     * @param string
     * @return
     */
    public static String tranformDate(String string) {
        String dateStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(string);
            dateStr = sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * EditText光标移动至末尾
     *
     * @param et EditText
     */
    public static void moveCursorToLast(EditText et) {
        if (null == et) {
            return;
        }
        int cursorIndex = et.getText().toString().length();
        et.setSelection(cursorIndex);
    }

    /**
     * @param edit
     * @param context
     * @Description:关闭软键盘
     */
    public static void closeInputMethod(Context context, View edit) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }

    /**
     * @param edit
     * @param context
     * @Description:关闭软键盘
     */
    public static void closeInputMethod(Context context, EditText edit) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        // edit.setCursorVisible(false);//失去光标
        edit.requestFocus();
        imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     *
     * @param ct
     * @param v
     */
    public static void showSoftkeyboard(Context ct, View v) {
        InputMethodManager imm = (InputMethodManager) ct.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
    }

    public static boolean isMobileNO(String phone) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();

    }

    public static String getFormatTime(String timestampString, String formats) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
        return date;
    }

    public static String getFormatTime(String timestampString) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(timestamp));
        return date;
    }

    public static String getFormatTime(int timestampInt) {
        long timestamp = timestampInt * 1000;
        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(timestamp));
        return date;
    }

    public static String getFormatTime(long timestampInt) {
        long timestamp = timestampInt * 1000;
        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(timestamp));
        return date;
    }

    /**
     * @param <E>
     * @Description:判断List是否为空 true为空的状态 false是不为空的状态
     */
    public static <E> boolean isNullForList(List<E> list) {
        boolean flag = true;
        if (list != null && list.size() > 0) {
            flag = false;
        }
        return flag;
    }

    /**
     * @param <E>
     * @Description:判断List是否为空 true为空的状态 false是不为空的状态
     */
    public static <E> boolean isNullForMap(Map<String, E> map) {
        boolean flag = true;
        if (map != null && map.size() > 0) {
            flag = false;
        }
        return flag;
    }

    /**
     * 没有从BaseActivity 继承下来的Activity，校验登录
     *
     * @return true为已经登录
     */
    public static boolean checkLogin(Activity activity) {
        if (PersistenceUtils.isLogin()) {
            return true;
        } else {
            Intent loginIntent = new Intent(activity, NewLoginActivity.class);
            activity.startActivity(loginIntent);
            activity.finish();
            return false;
        }
    }

    public static void logout() {
        EventBus.getDefault().post(new Intent(Constants.ACTION_USER_CHANGE));
        Settings.delUser(String.valueOf(Global.currentUser.id));
        Global.currentUser = null;
    }

    /**
     * 清除登录信息
     */
    public static void clearLogin() {
        if (Global.currentUser != null) {
            Settings.delUser(String.valueOf(Global.currentUser.id));
            Global.currentUser = null;
        }
    }

    public static String saveFileToGetPath(Activity activity, Bitmap bmp) throws IOException {
        String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        String subForder = SAVE_REAL_PATH;
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return myCaptureFile.getAbsolutePath();
    }

    /**
     * 保存图片到相册
     *
     * @param bm
     * @throws IOException
     */
    public static void saveFile(Activity activity, Bitmap bm) throws IOException {
        String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
        String subForder = SAVE_REAL_PATH;
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();


        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        activity.sendBroadcast(intent);
    }

    public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    public static void launchShareActivity(Activity activity, String title, String url,
                                           String imageUrl, String description, Bitmap image) {
        Intent intent = new Intent(activity, ShareActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        Bitmap bmp = ImageUtils.getWeChatShareBitmap(image);
        if (bmp != null)
            intent.putExtra("image", bmp);
        if (imageUrl != null)
            intent.putExtra("imageUrl", imageUrl);
        if (description != null)
            intent.putExtra("description", description);
        activity.startActivity(intent);
        //        activity.overridePendingTransition(R.anim.activity_open, 0);
    }


    /**
     * 获得格式化的时间 中间四位隐藏
     */
    public static String getFormatMobile(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            return "";
        }

        if (mobile.length() < 4) {
            return mobile;
        }

        String medium4String = mobile.substring(3, 7);
        return mobile.replace(medium4String, "****");
    }

    /**
     * 获得当前版本号
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pkgMng = context.getPackageManager();
            PackageInfo pkgInfo = pkgMng.getPackageInfo(context.getPackageName(), 0);
            versionName = pkgInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获得格式化数量
     *
     * @param number
     * @return 大于99 显示99+
     */
    public static String getFormaterNumber(int number) {
        return number > 99 ? "99+" : String.valueOf(number);
    }

    /**
     * 获得格式化数量
     *
     * @param numberStr
     * @return 大于99 显示99+
     */
    public static String getFormaterNumber(String numberStr) {
        try {
            return getFormaterNumber(Integer.parseInt(numberStr));
        } catch (NumberFormatException e) {
            return numberStr;
        }
    }


    /**
     * 获得独一无二的Psuedo ID
     *
     * @return
     */
    public static String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
